package com.parsec.sb.spring.async;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

@Component
public class AsyncTask {
    @Async
    public void runTask1() {
        try {
            System.out.println("Start Task 1 ...");
            long start = System.currentTimeMillis();
            int second = 10 * 1000;
            Thread.sleep(second);
            long end = System.currentTimeMillis();
            System.out.println("Over Task 1, Run Time: " + (end-start) + "ms");
        } catch (Exception e) {
            System.out.println("Exit Task 1");
        }
    }

    @Async
    public void runTask2() {
        try {
            System.out.println("Start Task 2 ...");
            long start = System.currentTimeMillis();
            int second = 5 * 1000;
            Thread.sleep(second);
            long end = System.currentTimeMillis();
            System.out.println("Over Task 2, Run Time: " + (end-start) + "ms");
        } catch (Exception e) {
            System.out.println("Exit Task 2");
        }
    }

    @Async
    public Future<String> runTask(String taskName, Integer taskSecond) {
        String result = null;
        try{
            System.out.println("Start: "+ taskName + " ...");
            long start = System.currentTimeMillis();
            Thread.sleep(taskSecond * 1000);
            long end = System.currentTimeMillis();
            result = taskName +", Run Time: " + (end - start)/1000 + " s";
            System.out.println("Over: " + result);
        } catch (Exception e) {
            System.out.println( taskName +" have error");
        }
        return new AsyncResult<>(result);
    }
}
